toastr.options = {
    closeButton: true,
    progressBar: true,
    showMethod: 'slideDown',
    timeOut: 4000,
};

$(document).ajaxSend(function (event, jqxhr, settings) {
    if (settings.submitControl && !settings.submitControl.go()) {
        jqxhr.abort();
    }
});

$(document).ajaxComplete(function (event, xhr, settings) {
    if (settings.submitControl) {
        settings.submitControl.done();
    }
});

$(document).ajaxError(function (event, jqxhr, settings, exception) {
    switch (jqxhr.status) {
        case 500:
            layui.layer.msg('服务器异常');
            break;
        case 401:
            location.reload();
            break;
        case 422:
            !settings.noValidate && showValidateErrors(jqxhr.responseJSON, settings.toastValidate, settings.form);
            break;
        default:
        // null
    }
});

// layui的输入弹框,直接按回车确认
$(document).on('keydown', '.layui-layer-prompt input', function (e) {
    var self = $(this);
    if (e.key == 'Enter') {
        self.closest('.layui-layer-prompt').find('.layui-layer-btn0').triggerHandler('click');
    }
});

$.extend($.fn.editable.defaults, {
    emptytext: '',
    params: function (params) {
        params._token = laravel.token;
        params._editable_ = 1;
        params._method = 'PUT';
        params._stay_ = true;
        return params;
    },
    ajaxOptions: {
        noValidate: true,
    },
    error: function (res) {
        if (res.status == 422) {
            var errorMsg = '';
            $.each(res.responseJSON.errors, function (_, errors) {
                $.each(errors, function (_, error) {
                    errorMsg += (errorMsg ? ('\n' + error) : error);
                });
            });

            return errorMsg;
        }
    },
    success: function () {
        toastr.success('更新成功');
    },
});

$.fn.editableform.buttons =
    '<div class="layui-btn-group">' +
    '<button type="submit" class="editable-submit layui-btn layui-btn-sm">保存</button>\n' +
    '<button type="button" class="editable-cancel layui-btn layui-btn-sm layui-btn-primary">取消</button>' +
    '</div>';

layui.use(['layer', 'form', 'element'], function () {
    var layer = layui.layer;
    var form = layui.form;
    var element = layui.element;

    // 切换每页数量 开始
    form.on('select(changePerPage)', function (e) {
        var val = e.value;
        if (val) {
            var url = new objURL;
            location.href = url.set('_per_page', val).remove('_page').url();
        } else {
            layer.prompt({
                title: '请输入每页的数量',
            }, function (value, index, elem) {
                var url = new objURL;
                location.href = url.set('_per_page', value).remove('_page').url();
                layer.close(index);
            });
        }
    });


    var perPageSelect = $('._perPage');

    // 选择了页数,自动切换
    perPageSelect.change(function () {
        var val = this.value;
        if (val) {
            var url = new objURL;
            location.href = url.set('_per_page', val).remove('_page').url();
        }
    });

    // 选择option中的其他,则弹出输入框
    perPageSelect.click(function (e) {
        // offsetY < 0 表示点击在select的option上
        if (e.offsetY < 0 && !this.value) {
            layer.prompt({
                title: '请输入每页的数量',
            }, function (value, index, elem) {
                var url = new objURL;
                location.href = url.set('_per_page', value).remove('_page').url();
                layer.close(index);
            });
        }
    });
    // 切换每页数量 结束

    // 跳到指定页 开始
    $('[name=_page]').keydown(function (e) {
        if (e.key == 'Enter') {
            var value = this.value;
            var url = new objURL;
            location.href = url.set('_page', value).url();
        }
    });

    $('._goPage').click(function () {
        var self = $(this);
        var value = self.closest('.layui-laypage-skip').find('[name=_page]').val();
        var url = new objURL;
        location.href = url.set('_page', value).url();
    });
    // 跳到指定页 结束

    // 刷新按钮 开始
    $('._refresh').click(function () {
        location.reload();
    });
    // 刷新按钮 结束

    // 复选框 全选操作 开始
    // 初始化已选的复选框数量
    var checkedCount = {};
    $('[lay-filter=select-item]:checked').each(function () {
        var self = $(this);
        var groupId = self.attr('select-item');
        if (checkedCount[groupId] === undefined) {
            checkedCount[groupId] = 0;
        }

        if (this.checked) {
            checkedCount[groupId]++;
        }
    });
    // 初始化全选和非全选状态
    for (var groupId in checkedCount) {
        if ($('[select-item=' + groupId + ']').length == checkedCount[groupId]) {
            $('[select-all=' + groupId + ']').prop('checked', true);
        }
    }
    form.render('checkbox');

    // 全选和非全选
    form.on('checkbox(select-all)', function (data) {
        var self = $(data.elem);
        var groupId = self.attr('select-all');
        var items = $('[select-item=' + groupId + ']');

        if (data.elem.checked) {
            items.prop('checked', true);
            checkedCount[groupId] = items.length;
        } else {
            items.prop('checked', false);
            checkedCount[groupId] = 0;
        }

        form.render('checkbox');
    });

    // 单选其他的改变全选框状态
    form.on('checkbox(select-item)', function (data) {
        var self = $(data.elem);
        var groupId = self.attr('select-item');
        var items = $('[select-item=' + groupId + ']');
        var checkAll = $('[select-all=' + groupId + ']');

        if (checkedCount[groupId] === undefined) {
            checkedCount[groupId] = 0;
        }

        if (data.elem.checked) {
            checkedCount[groupId]++;
        } else {
            checkedCount[groupId]--;
        }

        if (checkedCount[groupId] == items.length) {
            checkAll.prop('checked', true);
        } else {
            checkAll.prop('checked', false);
        }

        form.render('checkbox');
    });

    /**
     * 全选操作中,已选择的复选框对应的id数组
     * @returns {Array}
     */
    var selectedRows = function () {
        var selected = [];
        $('[select-item]:checked').each(function () {
            selected.push($(this).data('id'));
        });

        return selected;
    };
    // 复选框 全选操作 结束

    // 按历史记录返回按钮
    $('.form-history-back').click(function () {
        event.preventDefault();
        history.back();
    });

    // 批量删除 开始
    $('.grid-batch-delete').click(function () {
        var self = $(this);
        var selected = selectedRows();
        var resource = self.data('resource') + selected.join();

        var confirmMsg;
        if (selected.length > 0) {
            confirmMsg = '删除' + selected.length + '条记录？';
        } else {
            confirmMsg = '删除所有记录？';
        }

        layer.confirm(confirmMsg, {icon: 0, title: '警告'}, function (index) {
            $.ajax({
                method: 'post',
                url: resource,
                data: {
                    _method: 'delete',
                    _token: laravel.token,
                },
                success: function (res) {
                    if (res.status) {
                        location.reload();
                    }
                },
            });

            layer.close(index);
        });
    });
    // 批量删除 结束

    // 删除表格中的一条记录
    $('.grid-row-delete').unbind('click').click(function () {
        var id = $(this).data('id');
        var resource = $(this).data('resource');
        layer.confirm('确认删除？', {icon: 0, title: '警告'}, function (index) {
            $.post(resource + id, {_method: 'delete', '_token': laravel.token}, function (data) {
                if (data.status) {
                    location.reload();
                }
            });

            layer.close(index);
        });
    });

    // 通用表单提交
    var adminForm = $('.admin-form,.grid-form');
    // 表单中的上传组件
    adminForm.up = [];
    var sc = submitControl();
    sc.setForm(adminForm);

    adminForm.find(':submit').prop('disabled', false);
    adminForm.submit(function () {
        function ajaxSubmit() {
            adminForm.ajaxSubmit({
                form: adminForm,
                submitControl: sc,
                success: function (res) {
                    if (res.status && res.action) {
                        sc.setReset({
                            form: false,
                            status: false,
                        });
                        location.href = res.action;
                    }
                },
            });
        }

        // 表提交前,先自动上传
        var unUploaded = [];
        $.each(adminForm.up, function (_, _up) {
            $.each(_up.uploaders, function (_, up) {
                if (up.file && up.file.percent != 100) {
                    unUploaded.push(up);
                }
            });
        });

        if (unUploaded.length > 0) {
            layer.confirm('有文件还没上传,请确认', {
                title: '提示',
                btn: ['继续提交', '上传', '取消'],
                yes: function (index) {
                    ajaxSubmit();
                    layer.close(index);
                },
                btn2: function () {
                    $.each(unUploaded, function (_, up) {
                        up.start();
                    });
                },
            });
        } else {
            ajaxSubmit();
        }

        return false;
    });

    // 表单元素输入内容,则清空错误消息
    $('input,textarea').on('input', function () {
        clearValidateErrors($(this));
    });

    form.on('checkbox(admin-form-item)', function (data) {
        clearValidateErrors($(data.elem));
    });

    form.on('select(admin-form-item)', function (data) {
        clearValidateErrors($(data.elem));
    });

    // 表格中开关的切换
    form.on('switch(grid-switch)', function (data) {
        var self = $(data.elem);
        var values = self.data('values');
        var value = data.elem.checked ? values.on : values.off;

        var sc = submitControl();
        sc.setInputs(self);
        sc.noLoading();
        $.ajax({
            url: self.data('resource'),
            method: 'post',
            toastValidate: true,
            data: {
                _stay_: true,
                _token: laravel.token,
                _method: 'put',
                _editable_: true,
                name: self.data('name'),
                value: value,
            },
            submitControl: sc,
        }).done(function (res) {
            toastr.success('更新成功');
        }).fail(function (res) {
            self.prop('checked', !data.elem.checked);
            form.render('checkbox');
        });
    });

    // 表格搜索折叠面板操作
    var searchCollapseBtn = $('[data-target="#search-form-collapse"]');
    var searchCollapseContent = $('#search-form-collapse');

    var searchPanelShown = localStorage.getItem('searchPanelShown');
    if (searchPanelShown === null || searchPanelShown == 1) {
        searchCollapseBtn.addClass('collapse-in');
        searchCollapseContent.addClass('in');
    }

    searchCollapseContent.on('show.bs.collapse hide.bs.collapse shown.bs.collapse hidden.bs.collapse', function (event) {
        switch (event.type) {
            case 'show':
                searchCollapseBtn.addClass('collapse-in');
                break;
            case 'hide':
                searchCollapseBtn.removeClass('collapse-in');
                break;
            case 'shown':
                localStorage.setItem('searchPanelShown', 1);
                break;
            case 'hidden':
                localStorage.setItem('searchPanelShown', 0);
                break;
            default:
            // null
        }
    });

    // 导出所选记录的操作
    $('._export-selected').click(function (event) {
        event.preventDefault();

        var rows = selectedRows().join(',');
        if (!rows) {
            layer.msg('请选择需要导出的记录');
            return false;
        }

        var href = $(this).attr('href').replace('__rows__', rows);
        location.href = href;
    });

    /**
     * plupload中为我们提供了mOxie对象
     * 有关mOxie的介绍和说明请看：https://github.com/moxiecode/moxie/wiki/API
     * 来自：http://chaping.github.io/plupload/demo/index4.html
     *
     * @param file plupload事件监听函数参数中的file对象
     * @param callback 预览图片准备完成的回调函数
     */
    function previewImage(file, callback) {
        // 确保文件是图片
        if (!file || !/image\//.test(file.type)) {
            callback && callback();
            return;
        }
        // gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
        if (file.type == 'image/gif') {
            var fr = new moxie.file.FileReader();
            fr.onload = function () {
                callback && callback(fr.result);
                fr.destroy();
                fr = null;
            };
            fr.readAsDataURL(file.getSource());
        } else {
            var preloader = new moxie.image.Image();
            preloader.onload = function () {
                // 先压缩一下要预览的图片,宽300，高300
                preloader.downsize(300, 300);
                // 得到图片src,实质为一个base64编码的数据
                var imgsrc = preloader.type == 'image/jpeg'
                    ? preloader.getAsDataURL('image/jpeg', 80)
                    : preloader.getAsDataURL();
                // callback传入的参数为预览图片的url
                callback && callback(imgsrc);
                preloader.destroy();
                preloader = null;
            };
            preloader.load(file.getSource());
        }
    }

    /**
     * Error事件处理函数
     *
     * @param up
     * @param res
     */
    function pluploadErrorCallback(up, res) {
        if (res.code == plupload.FILE_SIZE_ERROR) {
            layer.msg('文件不能大于 ' + up.getOption('filters').max_file_size);
        }
    }

    /**
     * 通过文件名获取文件后缀
     *
     * @param filename
     * @returns {string}
     */
    function getFileExt(filename) {
        var ext = filename.split('.').pop();

        return ext ? ext : '';
    }

    function pluploadDestroyCallback(up) {
        var c = up.controller;
        delete c.uploaders[up.preview.html.data('uploader-id')];
        up.preview.html.remove();

        if (!c.checkMaxNum()) {
            $(c.getOption('browse_button')).parent().show();
        }
    }

    // 返回真正用来执行上传的配置
    var realUploaderOptions = function (id, fieldName, options) {
        return {
            multi_selection: false,
            runtimes: options.runtimes,
            browse_button: id,
            file_data_name: fieldName,
            url: options.url,
            chunk_size: options.chunk_size,
            unique_names: true,
            multipart_params: options.multipart_params,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                Accept: 'application/json',
            },
            // container: '.file-preview',

            // resize: {width: 300, quality: 90},

            filters: options.filters,

            flash_swf_url: options.flash_swf_url,

            init: {
                BeforeUpload: function (up, file) {
                    // 每次分片上传成功后,会设置file.realLoaded的值,表示真正上传完毕的字节数量
                    file.loaded = file.realLoaded;
                },

                StateChanged: function (up, file) {
                    clearValidateErrors(up.preview.html);

                    // 进度条状态
                    if (up.file.status == plupload.DONE) {
                        up.preview.progressBarHtml.removeClass().addClass('layui-progress-bar layui-bg-green');
                    } else {
                        up.preview.progressBarHtml.removeClass().addClass('layui-progress-bar layui-bg-red');
                    }

                    // 开始暂停预览按钮状态
                    if (up.file.status == plupload.DONE) {
                        up.preview.otherActionHtml.removeClass().addClass('action other view');
                    } else if (up.state == plupload.STOPPED) {
                        up.preview.otherActionHtml.removeClass().addClass('action other start');
                    } else if (up.state == plupload.STARTED) {
                        up.preview.otherActionHtml.removeClass().addClass('action other stop');
                    }
                },

                ChunkUploaded: function (up, file, info) {
                    // 反复批量开始和暂停后,会出现某个分片没上传,但是下一次恢复时,直接上传下一个分片的问题
                    // 当暂停后,这个回调执行不到,所以,真正已发送完的字节,还是上一次设置的,
                    // 所以可以重新发送被暂停取消了的分片
                    // 再配合后台采用把所有分片都保存,最后再合并的方法,确保不出错
                    file.realLoaded = file.loaded;

                    // 此处是真正上传完毕的字节百分比,progress的不准
                    element.progress(up.preview.progressLayFilter, file.percent + '%');
                },

                UploadComplete: function (up, files) {
                    // 小文件虽然也还会以分片的方式上传,但是不会触发'ChunkUploaded'事件
                    element.progress(up.preview.progressLayFilter, up.file.percent + '%');

                    if (up.file.status != plupload.FAILED) {
                        // up.htmlNode.css('border', '1px solid green');
                    }
                },

                Destroy: function (up) {
                    pluploadDestroyCallback(up);
                },

                FileUploaded: function (up, file, res) {
                    var data;
                    try {
                        data = JSON.parse(res.response);
                    } catch (e) {
                        log('file uploaded data parse error', e);
                        data = {};
                    }
                    if (data.status) {
                        var name = up.controller.fieldName;
                        name = up.controller.getOption('multi_selection') ? (name + '[]') : name;
                        up.preview.html.find('[name="' + name + '"]').remove();
                        up.preview.html.append('<input hidden readonly name="' + name + '" value="' + data.value + '">');
                        up.preview.imgContainerHtml.find('img').prop('src', data.src);
                    }
                }
            }
        };
    };

    // 一个表单中,不同的文件上传字段
    var fileInputs = $('.file-field');
    window.uploaderControllers = [];

    fileInputs.each(function () {
        var fileInput = $(this);
        var fieldName = fileInput.data('name');
        var options = fileInput.data('options');
        var existsFiles = fileInput.find('.file-preview');

        var uc = new plupload.Uploader({
            runtimes: options.runtimes,
            browse_button: fileInput.find('.pick-file').prop('id'),
            unique_names: true,
            flash_swf_url: options.flash_swf_url,
            multi_selection: options.multi_selection,
            filters: options.filters,
            init: {
                PostInit: function (up) {
                    fileInput.find('.start-all').click(function () {
                        plupload.each(up.uploaders, function (thisUp) {
                            thisUp.start();
                        });
                    });

                    fileInput.find('.stop-all').click(function () {
                        plupload.each(up.uploaders, function (thisUp) {
                            thisUp.stop();
                        });
                    });

                    fileInput.on('click', '.action.other,.cancel', function () {
                        var self = $(this);
                        var uploaderId = self.closest('[data-uploader-id]').data('uploader-id');
                        var uploader = up.uploaders[uploaderId];
                        if (self.hasClass('start')) {
                            uploader.start();
                        } else if (self.hasClass('stop')) {
                            uploader.stop();
                        } else if (self.hasClass('cancel')) {
                            try {
                                uploader.destroy();
                            } catch (e) {
                                pluploadDestroyCallback(uploader);
                            }
                        } else if (self.hasClass('view')) {
                            var images = up.filelist.find('.file-img img');
                            var thisImage = self.closest('.file-preview').find('.file-img img');
                            if (thisImage.length == 0) {
                                layer.msg('只有图片才能预览');

                                return;
                            }

                            var index = images.index(thisImage);
                            var data = [];
                            images.each(function () {
                                data.push({
                                    alt: '',
                                    pid: '',
                                    src: $(this).prop('src'),
                                    thumb: '',
                                });
                            });

                            layer.photos({
                                photos: {
                                    title: '图片预览',
                                    id: '',
                                    start: index,
                                    data: data,
                                },
                                anim: 5,
                            });
                        }
                    });
                },

                // 主控实例不允许上传
                BeforeUpload: function (up, file) {
                    up.stop();
                },

                StateChanged: function (up, file) {
                    clearValidateErrors(up.filelist);
                },

                FilesAdded: function (up, files) {
                    var msgShown = false;

                    plupload.each(files, function (file) {
                        if (up.checkMaxNum()) {
                            // 已经满了,如果再添加,则提示已经满了,并删除添加进来的文件
                            !msgShown && layer.msg('最多只能选择' + up.max_num + '项');
                            msgShown = true;
                            up.removeFile(file);

                            // 相当于continue
                            return;
                        }

                        var uniqueId = fieldName + up.uploaderIncrementId;
                        var pickId = 'upload-' + uniqueId;
                        var progressFilter = 'progress-' + uniqueId;
                        var previewHtml = $(
                            '<div class="file-preview" data-uploader-id="' + up.uploaderIncrementId + '">' +
                            '    <div class="file-img">' +
                            '        <img src="">' +
                            '    </div>' +
                            '    <div class="file-actions">' +
                            '        <div class="action other start"></div>' +
                            '        <div class="action change" id="' + pickId + '">更换</div>' +
                            '        <div class="cancel"><i class="fas fa-times"></i></div>' +
                            '    </div>' +
                            '    <div class="file-progress">' +
                            '        <div class="layui-progress layui-progress-big" lay-filter="' + progressFilter + '">' +
                            '            <div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>' +
                            '        </div>' +
                            '        <div class="filename layui-elip"></div>' +
                            '    </div>' +
                            '</div>'
                        );
                        $(up.getOption('browse_button')).parent().before(previewHtml);

                        var realUploader = new plupload.Uploader(realUploaderOptions(pickId, fieldName, options));
                        realUploader.init();

                        // 在前面的配置文件中,定义这个事件的方法,第一次加入文件时,不会触发
                        realUploader.bind('FilesAdded', function (up, files) {
                            clearValidateErrors(up.preview.html);

                            // 移除队列中除最后一个以外的所有文件
                            up.splice(0, up.files.length - 1);
                            up.stop();

                            var file = files[0];
                            element.progress(up.preview.progressLayFilter, file.percent + '%');
                            up.preview.fileNameHtml.text(file.name);
                            up.preview.fileNameHtml.attr('title', file.name);
                            up.preview.otherActionHtml.removeClass().addClass('action other start');
                            up.preview.html.find('[name=' + up.controller.fieldName + ']').remove();

                            // 单独一个属性引用该文件,仅仅为了方便获取
                            up.file = file;

                            // 预览
                            previewImage(file, function (imgSrc) {
                                if (imgSrc) {
                                    up.preview.imgContainerHtml.html('<img src="' + imgSrc + '">');
                                } else {
                                    var ext = getFileExt(file.name);
                                    up.preview.imgContainerHtml.html('<span>' + ext + '</span>');
                                }
                            });
                        });

                        realUploader.bind('Error', function (up, res) {
                            log('[Error] ', res);
                            switch (res.status) {
                                case 401:
                                    location.reload();
                                    break;
                                case 422:
                                    showValidateErrors(JSON.parse(res.response));
                                    break;
                                default:
                                    layui.layer.msg('服务器异常');
                            }
                            // up.htmlNode.css('border', '1px solid red');

                            pluploadErrorCallback(up, res);
                        });

                        realUploader.addFile(file);

                        realUploader.preview = {
                            html: previewHtml,
                            imgContainerHtml: previewHtml.find('.file-img'),
                            fileNameHtml: previewHtml.find('.filename'),
                            progressBarHtml: previewHtml.find('.layui-progress-bar'),
                            progressLayFilter: progressFilter,
                            otherActionHtml: previewHtml.find('.action.other'),
                        };
                        realUploader.controller = up;

                        // 重写start方法
                        realUploader._start = realUploader.start;
                        /**
                         * 强制开始,如果是失败的文件,则重置文件状态和已上传字节数,然后就可以重新开始上传
                         */
                        realUploader.start = function () {
                            // 如果文件失败,则重新上传
                            if (this.file.status == plupload.FAILED) {
                                // this.file.realLoaded = 0;
                                this.file.status = plupload.QUEUED;
                            }

                            this._start();
                        };

                        up.uploaders[up.uploaderIncrementId] = realUploader;
                        up.uploaderIncrementId++;

                        // 刚满的时候,直接隐藏掉选文件按钮
                        if (uc.checkMaxNum()) {
                            $(up.getOption('browse_button')).parent().hide();
                        }
                    });
                },

                UploadComplete: function (up, files) {
                    alert('all done');
                },

                Error: function (up, res) {
                    pluploadErrorCallback(up, res);
                }
            }
        });

        uc.filelist = fileInput.find('.file-list');
        uc.uploaders = {};
        uc.fieldName = fieldName;
        uc.uploaderIncrementId = 0;
        uc.max_num = options.max_num;
        uc.checkMaxNum = function () {
            return this.max_num > 0 && Object.keys(this.uploaders).length >= this.max_num;
        };

        uc.init();

        // 初始化预览
        existsFiles.each(function () {
            var previewHtml = $(this);
            var pickId = 'upload-' + fieldName + uc.uploaderIncrementId;

            var realUploader = new plupload.Uploader(realUploaderOptions(pickId, fieldName, options));
            realUploader.init();

            // 在前面的配置文件中,定义这个事件的方法,第一次加入文件时,不会触发
            realUploader.bind('FilesAdded', function (up, files) {
                clearValidateErrors(up.preview.html);

                // 移除队列中除最后一个以外的所有文件
                up.splice(0, up.files.length - 1);
                up.stop();

                var file = files[0];
                up.preview.progressLayFilter = up.preview.html.find('.layui-progress').attr('lay-filter');
                element.progress(up.preview.progressLayFilter, file.percent + '%');
                up.preview.fileNameHtml.text(file.name);
                up.preview.fileNameHtml.attr('title', file.name);
                up.preview.otherActionHtml.removeClass().addClass('action other start');
                up.preview.html.find('[name=' + up.controller.fieldName + ']').remove();

                // 单独一个属性引用该文件,仅仅为了方便获取
                up.file = file;

                // 预览
                previewImage(file, function (imgSrc) {
                    if (imgSrc) {
                        up.preview.imgContainerHtml.html('<img src="' + imgSrc + '">');
                    } else {
                        var ext = getFileExt(file.name);
                        up.preview.imgContainerHtml.html('<span>' + ext + '</span>');
                    }
                });
            });

            realUploader.bind('Error', function (up, res) {
                log('[Error] ', res);
                switch (res.status) {
                    case 401:
                        location.reload();
                        break;
                    case 422:
                        showValidateErrors(JSON.parse(res.response));
                        break;
                    default:
                        layui.layer.msg('服务器异常');
                }
                // up.htmlNode.css('border', '1px solid red');

                pluploadErrorCallback(up, res);
            });

            realUploader.preview = {
                html: previewHtml,
                imgContainerHtml: previewHtml.find('.file-img'),
                fileNameHtml: previewHtml.find('.filename'),
                progressBarHtml: previewHtml.find('.layui-progress-bar'),
                progressLayFilter: 'progress-' + uc.uploaderIncrementId,
                otherActionHtml: previewHtml.find('.action.other'),
            };
            realUploader.controller = uc;

            // 重写start方法
            realUploader._start = realUploader.start;
            /**
             * 强制开始,如果是失败的文件,则重置文件状态和已上传字节数,然后就可以重新开始上传
             */
            realUploader.start = function () {
                // 如果文件失败,则重新上传
                if (this.file.status == plupload.FAILED) {
                    // this.file.realLoaded = 0;
                    this.file.status = plupload.QUEUED;
                }

                this._start();
            };

            uc.uploaders[uc.uploaderIncrementId] = realUploader;
            uc.uploaderIncrementId++;
        });

        if (!uc.checkMaxNum()) {
            $(uc.getOption('browse_button')).parent().show();
        }

        uploaderControllers.push(uc);
        adminForm.up = uploaderControllers;
    });

});
